/**
 * @format
 * @Author: TC
 * @Date: 2023-08-18 23:16:00
 * @Last Modified by: TC
 * @Last Modified time: 2023-08-21 17:00:33
 */

import { Vec2, v2 } from "cc";
import { app } from "../../App";
import { IBaseInterface, IV2 } from "../../Interface/BaseInterface";
import { INavCoord, INavPolygon } from "./NavInterface";

/**
 * 多边形单位
 */
export class PolygonUnit implements IBaseInterface {
    public f: number = 0;
    private g: number = 0;
    private h: number = 0;
    private _iPolygon: INavPolygon = null;
    public parent: PolygonUnit = null;

    public neighbourArr: PolygonUnit[] = [];

    public walkable: boolean = true;

    public set polygon(p: INavPolygon) {
        this._iPolygon = p;
    }

    public get polygon(): INavPolygon {
        return this._iPolygon;
    }

    private getPointArr(): [number, number][] {
        let arr: [number, number][] = [];
        if (this._iPolygon) {
            this._iPolygon.coords.forEach((c) => {
                arr.push([c.x, c.y]);
            });
        }
        return arr;
    }

    public pointInPolygon(x: number, y: number): boolean {
        return app.mMath.pointInPolygon(x, y, this.getPointArr());
    }

    /**
     * 判断是否邻居多边形
     * @param p
     */
    public isHeighbour(p: PolygonUnit): boolean {
        let cnt = 0; //公共节点数
        this.polygon.coords.forEach((cSelf) => {
            p.polygon.coords.forEach((cOther) => {
                if (cSelf == cOther) {
                    cnt++;
                }
            });
        });
        return cnt == 2;
    }

    /**
     * 获取与邻居的公共顶点
     * @param otherPolygon
     * @returns
     */
    public getPublicCoords(otherPolygon: PolygonUnit): INavCoord[] {
        let coords: INavCoord[] = [];
        this.polygon.coords.forEach((cSelf) => {
            otherPolygon.polygon.coords.forEach((cOther) => {
                if (cSelf == cOther) {
                    coords.push(cSelf);
                }
            });
        });
        return coords;
    }

    /**
     * 计算FGH
     * @param curr
     * @param endPos
     */
    public calFGH(curr: PolygonUnit, endPos: IV2): void {
        curr.g = Math.abs(Vec2.distance(curr.getCenter(), this.getCenter()));
        curr.h = Math.abs(Vec2.distance(this.getCenter(), endPos));
        curr.f = curr.g + curr.h;
    }

    /**
     * 获取中心点坐标
     */
    public getCenter(): IV2 {
        let len = this._iPolygon.coords.length;
        let center: IV2 = {
            x: 0,
            y: 0,
        };
        for (let i = 0; i < len; i++) {
            center.x += this._iPolygon.coords[i].x;
            center.y += this._iPolygon.coords[i].y;
        }
        center.x /= len;
        center.y /= len;
        return center;
    }

    release(): void {}
}
